import store from "@/store";
import Vue from "vue";
import i18n from "@/locale";
import dayjs from "dayjs";

export function debounce(callback, time) {
    let timer;
    return function () {
        if (timer) clearTimeout(timer)
        timer = setTimeout(() => {
            callback.apply((this))
        }, time)
    }
}

// 清除缓存
export function cleanCache() {
    Vue.prototype.$permiss = {}
    store.dispatch('clearCache')
    sessionStorage.clear()
}

/**
 * 无权限的接口拦截请求
 */
export function requestFilter(url) {
    const menuList = JSON.parse(sessionStorage.getItem('menuList') || "[]")
    const flag = menuList.some(item => item.url === url)
    return flag
}

export function formaterTree(list) {
    return list.filter(father => {
        const childArr = list.filter(child => father.id === child.parentId)
        if (childArr.length > 0) {
            father.children = childArr
        }
        return father.parentId === 0
    })
}

export function dateFormat(date, fmt = 'YYYY-mm-dd HH:MM:SS') {
    let ret;
    const opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        }
    }
    return fmt;
}

//处理默认选中当前日期
export function getNowTime(data) {
    let now = data;
    let year = now.getFullYear(); //得到年份
    let month = now.getMonth(); //得到月份
    let date = now.getDate(); //得到日期
    // var hour =" 00:00:00"; //默认时分秒 如果传给后台的格式为年月日时分秒，就需要加这个，如若不需要，此行可忽略
    let hour = now.getHours();       //获取当前小时数(0-23)
    let minutes = now.getMinutes();     //获取当前分钟数(0-59)
    let seconds = now.getSeconds();     //获取当前秒数(0-59)

    hour = hour < 10 ? "0" + hour : hour;
    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    month = month + 1;
    month = month.toString().padStart(2, "0");
    date = date.toString().padStart(2, "0");
    let defaultDate = `${year}-${month}-${date} ${hour}:${minutes}:${seconds}`;
    return defaultDate;
}


// 深拷贝
export function deepClone(data) {
    let result
    if (typeof data === 'object') {
        if (Array.isArray(data)) {
            result = []
            for (let i = 0; i < data.length; i++) {
                result.push(deepClone(data[i]))
            }
        } else if (data === null) {
            result = null
        } else if (data.constructor === RegExp) {
            result = data
        } else if (data.constructor === Date) {
            result = data.getTime()
        } else {
            result = {}
            for (let i in data) {
                result[i] = deepClone(data[i])
            }
        }
    } else {
        result = data
    }
    return result
}

/**
 *  格式化金额函数
 * @param number
 * @param places
 * @param symbol
 * @param thousand
 * @param decimal
 * @return {string}
 */
export function formatMoney(number, places, symbol, thousand, decimal) {
    number = number || 0;
    places = !isNaN(places = Math.abs(places)) ? places : 2;
    symbol = symbol !== undefined ? symbol : "$";
    thousand = thousand || ",";
    decimal = decimal || ".";
    var negative = number < 0 ? "-" : "",
        i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
}

// 处理接口请求权限
export function permissProcess(url, permiss) {
    const permissSum = {...permiss}
    const arr = []
    for (let i in permissSum) {
        // 去掉斜杠
        arr.push(permissSum[i].substr(1, permissSum[i].length - 1))
    }
    return arr.indexOf(url) !== -1
}

// 下拉原因标签数组
export function reasonTagsList() {
    // 提醒，催收原因标签数组
    const collectionList = [
        {key: 1, value: i18n.t('意向客户')},
        {key: 2, value: i18n.t('拒绝还款')},
        {key: 3, value: i18n.t('跳票客户')},
        {key: 4, value: i18n.t('联系不上')},
        {key: 5, value: i18n.t('第三方转告')},
        {key: 6, value: i18n.t('争议客户')},
        {key: 7, value: i18n.t('其他'), isRemarks: 1}
    ]
    const collectionTagsList = [
        {key: 1, value: i18n.t('今日意向客户'), pid: 1, isTime: 1},
        {key: 2, value: i18n.t('非今日意向客户'), pid: 1, isTime: 1},
        {key: 3, value: i18n.t('骗贷客户'), pid: 2},
        {key: 4, value: i18n.t('其他'), pid: 2, isRemarks: 1},
        {key: 5, value: i18n.t('首次跳票'), pid: 3},
        {key: 6, value: i18n.t('多次跳票'), pid: 3},
        {key: 7, value: i18n.t('未接听'), pid: 4},
        {key: 8, value: i18n.t('关机'), pid: 4},
        {key: 9, value: i18n.t('停机'), pid: 4},
        {key: 10, value: i18n.t('拒接'), pid: 4},
        {key: 11, value: i18n.t('需减免'), pid: 6},
        {key: 12, value: i18n.t('其他'), pid: 6, isRemarks: 1},
    ]
    return {
        collectionList,
        collectionTagsList,
    }
}

/**
 * 防抖函数
 * @param fn
 * @param wait time
 * @param immediate 是否立即执行
 * @returns {function(): void}
 */
export function immediatelyDebounce(fn, wait = 1000, immediate = true) {
    let timer;
    return function () {
        if (timer) clearTimeout(timer);
        if (immediate) {
            // 如果已经执行过，不再执行
            var callNow = !timer;
            timer = setTimeout(() => {
                timer = null;
            }, wait)
            if (callNow) {
                fn.apply(this, arguments)
            }
        } else {
            timer = setTimeout(() => {
                fn.apply(this, arguments)
            }, wait);
        }
    }
}

/**
 *  设置各国时区
 * @returns {Date}
 */
export function setTimeZone() {
    /**
     * 判断当前环境国家
     *  默认中国时区
     */
    const REGION = process.env.VUE_APP_REGION
    let value = ''
    if (REGION === 'moxige') {
        value = 'MXG'
    } else if (REGION === 'yuenan') {
        value = 'YN'
    } else {
        value = 'ZG'
    }
    /**
     * YN 东七区 越南时区
     * MXG 西八区 墨西哥时区
     * ZG 东八区 中国时区
     */
    const zoneObj = {
        'YN': 7,
        'MXG': -5,
        'ZG': 8,
    }
    const zoneOffset = zoneObj[value]
    //算出时差,并转换为毫秒
    const offset2 = new Date().getTimezoneOffset() * 60 * 1000;
    //算出现在的时间
    const nowDate2 = new Date().getTime();
    const currentZoneDate = new Date(nowDate2 + offset2 + zoneOffset * 60 * 60 * 1000);
    return currentZoneDate
}

/**
 * 获取时间区间
 * num 提前的天数
 * @returns {Array}
 */
export function defaultTimeDate(num = 7, fmt = 'YYYY-MM-DD') {
    const daysNum = dayjs().date()
    const beforeDate = dayjs().date(daysNum - (num - 1))
    return [dayjs(beforeDate.$d).format(fmt), dayjs(new Date()).format(fmt)]
}


/**
 *  日期区间查询处理 包头包尾
 * @param timeArr {Array}
 * @return {*}
 */
export function dateFormatSection(timeArr) {
    const [beforeDate, afterDate] = timeArr || []
    if (beforeDate && afterDate) {
        // 结束时间增加一天
        const date = dateFormat(new Date(new Date(afterDate + ' 00:00:00').getTime() + (24 * 60 * 60 * 1000)), 'YYYY-mm-dd')
        return [beforeDate, date]
    } else {
        return []
    }
}
